<template>
  <breadCrumb ref="breadCrumbRef" :item="item"></breadCrumb>
  <div class="table-wrapped">
    <div class="table-top">
      <div class="table-header">
        <div></div>
        <div class="upload-wrapped">
          <el-upload v-model:file-list="fileList" class="upload-demo" action="http://127.0.0.1:3007/file/uploadFile"
            :headers="headers" multiple :limit='3' :on-exceed="handleExceed" :on-success="handleSuccess"
            :show-file-list='false'>
            <el-button type="primary">上传文件</el-button>
          </el-upload>
        </div>
      </div>
      <div class="table-content">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" width="50" />
          <el-table-column prop="file_name" label="文件名" />
          <el-table-column prop="afile_size" label="文件大小">
            <template #default="{ row }">
              <div>{{ row.file_size?.slice(0, 2) }} KB</div>
            </template>
          </el-table-column>
          <el-table-column prop="upload_person" label="上传者" />
          <el-table-column prop="download_number" label="下载次数" />
          <el-table-column prop="upload_time" label="上传时间" width="200">
            <template #default="{ row }">
              <div>{{ row.upload_time?.slice(0, 10) }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div>
                <el-button type="success">
                  <template #default>
                    <el-button @click="goDownLoad(row.download_number, row.id)"
                      style="background-color: transparent;border: none;color: white;padding: 5px;">下载</el-button>
                  </template>
                </el-button>
                <el-button type="danger" @click="goDelete(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="table-footer">
      <el-pagination :page-size="paginationData.filePageSize" :current-page="paginationData.fileCurrentPage"
        :total="paginationData.fileTotal" @current-change="goPagerChange" layout="prev, pager, next" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import breadCrumb from '../../components/breadCrumb.vue'
import { ref } from 'vue'
import { getFileListByPagerAPI, getFileListCountAPI, bindUploadPersonAPI, downloadFileAPI, deleteFileAPI, updateDownloadNumberAPI, getFileByIdAPI } from '../../api/file'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import FileSaver from 'file-saver'
import { tracking } from '../../utils/operate'

const breadCrumbRef = ref()

const item = ref({
  first: '合同管理',
  second: ''
})

const tableData = ref([])

const paginationData = ref({
  filePageSize: 5,
  fileCurrentPage: 1,
  fileTotal: 0
})


// 上传列表
const fileList = ref<UploadUserFile[]>([])

// 上传图片 超出限制时
const handleExceed = () => {

}
// 上传图片 成功时
const handleSuccess: UploadProps['onSuccess'] = (response: any) => {
  if (response.status == 0) {
    ElMessage({
      message: response.message,
      type: 'success'
    }),
      // 绑定上传者
      (async () => {
        const res = await bindUploadPersonAPI({ upload_person: JSON.parse(localStorage.getItem('userinfo') as string).name, file_url: response.url })
        console.log(res)
      })()

    // 提取文件名 以便传给 tracking
    let url = response.url
    let urlObject = new URL(url)
    let pathSegments = urlObject.pathname.split('/')
    let uploadIndex = pathSegments.indexOf('upload')
    let fileName = pathSegments[uploadIndex + 1] // 解码中文乱码
    let decodedFileName = decodeURIComponent(fileName)

    tracking("合同管理", "上传文件", { name: decodedFileName }, "中级")

  } else {
    ElMessage({
      message: response.message,
      type: 'error'
    })
  }
}

const token = localStorage.getItem('token')
const headers = {
  'Authorization': token
}

const fileName = ref('')

// 下载文件
const goDownLoad = async (download_number, id) => {
  const res1 = await getFileByIdAPI({ id })
  fileName.value = res1.data.data[0].file_name

  const res = await downloadFileAPI(id)

  FileSaver.saveAs(res.data, fileName.value)

  tracking("合同管理", "下载文件", { name: fileName.value }, "低级")

  const res2 = await updateDownloadNumberAPI({ download_number, id })
  if (res2.data.status == 0) {
    getFileListByPager()
  }
}

// 删除文件
const goDelete = async (row) => {

  const { id, file_name } = row

  const res1 = await getFileByIdAPI({ id })
  fileName.value = res1.data.data[0].file_name

  const res = await deleteFileAPI({ id, file_name })
  if (res.data.status == 0) {
    ElMessage({
      message: res.data.message,
      type: 'success'
    })
    getFileListByPager()
    tracking("合同管理", "删除文件", { name: fileName.value }, "高级")
  } else {
    ElMessage({
      message: res.data.message,
      type: 'error'
    })
  }
}


// 获取文件总数
const getFileListCount = async () => {
  const res = await getFileListCountAPI()
  paginationData.value.fileTotal = res.data.data
}
getFileListCount()

// 获取文件列表 (第一页)
const getFileListByPager = async () => {
  paginationData.value.fileCurrentPage = 1
  const res = await getFileListByPagerAPI({ pager: paginationData.value.fileCurrentPage })
  tableData.value = res.data.data

}
getFileListByPager()

// 分页
const goPagerChange = async (pager: number) => {
  paginationData.value.fileCurrentPage = pager
  const res = await getFileListByPagerAPI({ pager: paginationData.value.fileCurrentPage })
  tableData.value = res.data.data
}

</script>

<style lang="scss" scoped>
:deep(.el-table .cell) {
  font-weight: 400;
}

.upload-wrapped {
  margin-bottom: 10px;
}

a {
  color: #fff;
  display: block;
  text-decoration: none;
}

.table-footer {
  margin-top: 10px;
}
</style>
